package cn.spike.rockcc.exception;

import cn.spike.rockcc.result.JSONResult;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.List;

import static cn.spike.rockcc.errorenum.GlobalExceptionCode.PARAM_EXCEPTION;
import static cn.spike.rockcc.errorenum.GlobalExceptionCode.SYSTEM_EXCEPTION;


/**
 * 全局异常处理类
 * @author:spike
 * @create:2023-03-08 11:05
 */
//系统发生异常的时候 - 拦截请求
//@RestControllerAdvice = ResponseBody+ControllerAdvice
@RestControllerAdvice
public class GlobalExceptionHanler {

    /**
     *  @ExceptionHandler
        捕获具体类型异常进行处理
     */
    @ExceptionHandler(value = {Exception.class})
    public JSONResult error(Exception e){
        e.printStackTrace();
        return JSONResult.error(SYSTEM_EXCEPTION);
    }

    /**
     * 捕获业务异常并对其处理
     */
    @ExceptionHandler(value = {BusinessException.class})
    public JSONResult businessError(BusinessException ex){
        return JSONResult.error(ex);
    }

    /**
     * 捕获JSR303异常并对其处理
     */
    @ExceptionHandler(value = {MethodArgumentNotValidException.class})
    public JSONResult validError(MethodArgumentNotValidException ex){
        StringBuffer sb = new StringBuffer();
        List<ObjectError> errors = ex.getBindingResult().getAllErrors();
        errors.forEach(res->{
            String message = res.getDefaultMessage();
            sb.append(message).append(",");
        });
        sb.deleteCharAt(sb.length() - 1);
        return JSONResult.error(sb.toString(),PARAM_EXCEPTION.getCode());
    }

}
